#include "AppDelegate.h"
#include "SceneTitleLoading.h"

cocos2d::Scene * SceneTitleLoading::createScene()
{
	auto scene = Scene::create();
	auto layer = SceneTitleLoading::create();
	layer->setAnchorPoint(Point(0.5, 0.5));
	scene->addChild(layer);

	return scene;
}

bool SceneTitleLoading::init()
{
	if (!Layer::init())
	{
		return false;
	}
	addChild(LayerColor::create(Color4B::WHITE));
	createLogo();
	scheduleUpdate();
	return true;
}

void SceneTitleLoading::createLogo()
{
	auto act = FadeTo::create(1, 255);

	auto logo = Sprite::create("image/Logo.png");
	logo->setPosition(frameSize.width*.5f, frameSize.height*.5f);
	logo->setOpacity(0);
	addChild(logo);
	logo->runAction(act);

	string copyright = "Created by Dev.SakuyA\nPowered by Cocos2d-x & FMOD Ex";
	auto crlabel = Label::createWithTTF(copyright, FONTA, 30, Size::ZERO, TextHAlignment::CENTER);
	crlabel->setPosition(frameSize.width*.5f, frameSize.height*.35f);
	crlabel->setOpacity(0);
	crlabel->setTextColor(UICOMFGB);
	addChild(crlabel);
	crlabel->runAction(act->clone());

	info = Label::createWithTTF("LOADING", FONTB, 24);
	UI::setNodeAnch(info, ANCH_BL);
	info->setPosition(frameSize.width*.05f, frameSize.height*.2f);
	info->setTextColor(UICOMFGB);
	addChild(info);
	createDB();
}

void SceneTitleLoading::createDB(Label * labelInfo)
{
	thread([&]
	{
		this_thread::sleep_for(chrono::milliseconds(500));
		pDB = new DataBase(info);
		this_thread::sleep_for(chrono::milliseconds(500));
		isInit = true;
	}
	).detach();
}

void SceneTitleLoading::update(float dt)
{
	if (isInit)
	{
		unscheduleUpdate();
		gotoMainMenuScene();
	}
}

void SceneTitleLoading::gotoMainMenuScene()
{
	sceneSwitchMode = random(0, 3);
	auto uiss = UISceneSwitcher::create(UISS_MODE(sceneSwitchMode), LEAVE);
	addChild(uiss);
	uiss->play();
	runAction(
		Sequence::create(
			DelayTime::create(1.5f),
			CallFunc::create([&]
	{
		Director* director = Director::getInstance();
		pSceneMainMenu = SceneMainMenu::createScene();
		director->replaceScene(pSceneMainMenu);
	}),
			NULL
		)
	);
}
